package org.jflame.auth.authc.assist;

import org.jflame.context.cache.CacheWrapper;

import java.util.concurrent.atomic.AtomicInteger;

public class FailureCacheCounter extends FailureCounter {

    private CacheWrapper<String,AtomicInteger> cache;

    public FailureCacheCounter(CacheWrapper<String,AtomicInteger> _cache, int maxFailures) {
        super(maxFailures);
        cache = _cache;
    }

    @Override
    public int getFailures(String key) {
        AtomicInteger ai = cache.get(key);
        if (ai != null) {
            ai.get();
        }
        return 0;
    }

    @Override
    protected int increment(String key) {
        AtomicInteger ai = cache.get(key);
        if (ai != null) {
            return ai.incrementAndGet();
        } else {
            ai = new AtomicInteger(1);
            cache.put(key, ai);
            return 1;
        }
    }

    @Override
    public void clear(String account) {
        cache.evict(account);
    }

}
